package com.acooly.module.openapi.client.provider.fuyou.utils;

import com.acooly.core.utils.Encodes;
import com.acooly.core.utils.security.Cryptos;
import com.acooly.core.utils.security.RSA;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

/**
 * @author zhike 2018/3/19 18:26
 */
public class DESCoderFuyou {

    private static  String  CHATSET="UTF-8" ;
    //加密
    public static String desEncrypt(String input, String keystr) throws Exception {

        try {
            byte[] datasource = input.getBytes(CHATSET);
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(keystr.getBytes((CHATSET)));
            //创建一个密匙工厂，然后用它把DESKeySpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            //Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            //用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            //现在，获取数据并加密
            //正式执行加密操作
            return new BASE64Encoder().encode(cipher.doFinal(datasource)) ;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;

    }

    //解密
    public static String desDecrypt(String cipherText, String strkey) throws Exception {

        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(strkey.getBytes(CHATSET));
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作
        BASE64Decoder decoder = new BASE64Decoder();

        //b = decoder.decodeBuffer(src);
        return new String( cipher.doFinal(decoder.decodeBuffer(cipherText)),CHATSET);

    }

    /**
     *
     * @Title: getKeyLength8
     * @Description: (获取固定长度8的key)
     * @param @param key
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    public static String getKeyLength8(String key) {
        key = key == null ? "" : key.trim();
        int tt = key.length() % 64;

        String temp = "";
        for (int i = 0; i < 64 - tt; i++) {
            temp += "D";
        }
        return key + temp;

    }
}
